<template>
    <div>
        <van-index-bar :index-list="computedIndexList" @select="handleChange">
            <div v-for="data in cityList" :key="data.type">
                <van-index-anchor :index="data.type" />
                <van-cell :title="item.name" v-for="item in data.list" :key="item.cityId"
                 @click="handleCity(item)"/>
            </div>
        </van-index-bar>
    </div>
</template>
<script>
import http from '@/util/http'
import isShow from '@/util/mixinshow'
import { Toast } from 'vant'
export default {
  mixins: [isShow],
  // destroyed () {
  //   this.$store.commit('show')
  // },
  mounted () {
    // this.$store.commit('hide')
    http({
      url: '/gateway?k=2661646',
      headers: {
        'X-Host': 'mall.film-ticket.city.list'
      }
    }).then(res => {
    //   console.log(res.data.data.cities)
      //   定义一个函数 返回便利后的数组
      this.cityList = this.renderCity(res.data.data.cities)
    })
  },
  data () {
    return {
      cityList: []
    }
  },
  computed: {
    computedIndexList () {
      return this.cityList.map(item => item.type)
    }
  },
  methods: {
    handleChange (data) {
      Toast(data)
    },
    renderCity (list) {
      const cityList = []
      const letterList = []
      for (let i = 65; i < 91; i++) {
        letterList.push(String.fromCharCode(i))
      }

      letterList.forEach(letter => {
        const newList = list.filter(item => item.pinyin.substring(0, 1).toUpperCase() === letter)
        // console.log(newList)

        newList.length > 0 && cityList.push({
          type: letter,
          list: newList
        })
      })
      //   console.log(cityList)
      return cityList
    },
    handleCity (item) {
    //   this.$store.state.cityName = item.name
      this.$store.commit('changeCityName', item.name)
      this.$store.commit('changeCityId', item.cityId)
      this.$router.back()
    }
  }
}
</script>
<style lang="scss">
.van-toast--html, .van-toast--text{
    min-width: 30px;
}
</style>
